const { prisma } = require('../config/prisma');

/**
 * 获取分享参数
 */
const getShareParams = async (req, res) => {
  try {
    res.status(200).json({
      code: 200,
      data: {
        path: 'pages/index/index',
        query: `sharer=${req.user.id}`
      }
    });
  } catch (error) {
    console.error('Get share params error:', error);
    res.status(500).json({
      code: 500,
      message: '获取分享参数失败'
    });
  }
};

/**
 * 获取分享统计
 */
const getShareStats = async (req, res) => {
  try {
    const now = new Date();
    const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

    // 获取总邀请人数
    const totalInvites = await prisma.shareRecord.count({
      where: {
        sharerId: req.user.id
      }
    });

    // 获取本月邀请人数
    const monthInvites = await prisma.shareRecord.count({
      where: {
        sharerId: req.user.id,
        createdAt: {
          gte: firstDayOfMonth
        }
      }
    });

    // 计算总获得奖励天数
    const totalRewardDays = totalInvites * 7;

    // 计算本月剩余可获得奖励次数
    const monthRemainTimes = Math.max(0, 10 - monthInvites);

    res.status(200).json({
      code: 200,
      data: {
        total_invites: totalInvites,
        month_invites: monthInvites,
        total_reward_days: totalRewardDays,
        month_remain_times: monthRemainTimes
      }
    });
  } catch (error) {
    console.error('Get share stats error:', error);
    res.status(500).json({
      code: 500,
      message: '获取分享统计失败'
    });
  }
};

/**
 * 处理分享奖励
 * @param {string} sharerId - 分享人ID
 * @param {string} inviteeId - 被邀请人ID
 * @param {number} scene - 场景值
 */
const handleShareReward = async (sharerId, inviteeId, scene) => {
  const now = new Date();
  const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

  // 检查是否是新用户
  const inviteeShareRecord = await prisma.shareRecord.findFirst({
    where: {
      inviteeId
    }
  });

  if (inviteeShareRecord) {
    return false;
  }

  // 检查分享人本月是否达到上限
  const monthInvites = await prisma.shareRecord.count({
    where: {
      sharerId,
      createdAt: {
        gte: firstDayOfMonth
      }
    }
  });

  if (monthInvites >= 10) {
    return false;
  }

  // 开启事务处理
  await prisma.$transaction(async (prisma) => {
    // 创建分享记录
    await prisma.shareRecord.create({
      data: {
        sharerId,
        inviteeId,
        scene,
        rewardDays: 7
      }
    });

    // 更新分享人会员时长
    const sharer = await prisma.user.findUnique({
      where: { id: sharerId }
    });

    let sharerExpireTime;
    if (sharer.memberType > 0 && sharer.expireTime > now) {
      sharerExpireTime = new Date(sharer.expireTime.getTime() + 7 * 24 * 60 * 60 * 1000);
    } else {
      sharerExpireTime = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    }

    await prisma.user.update({
      where: { id: sharerId },
      data: {
        memberType: 1,
        expireTime: sharerExpireTime
      }
    });

    // 更新被邀请人会员时长
    const inviteeExpireTime = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    await prisma.user.update({
      where: { id: inviteeId },
      data: {
        memberType: 1,
        expireTime: inviteeExpireTime
      }
    });
  });

  return true;
};

module.exports = {
  getShareParams,
  getShareStats,
  handleShareReward
}; 